<template>
  <el-dialog
    :close-on-click-modal="false"
    title="扫码装箱"
    :visible.sync="dialogTablesVisible"
    :modal-append-to-body="false"
    id="equmentBatch">
    <template>
      <el-tabs type="card" id="tabCard" >
        <div>
          <el-steps :active="disc_current" simple finish-status="success">
            <el-step title="创建箱号"></el-step>
            <el-step title="选择设备"></el-step>
            <el-step title="装箱完成"></el-step>
          </el-steps>
          <!-- 第一步分开分配 -->
          <el-row id="firstCard" v-if="disc_current === 1">
            <div class="firststorage">
              <el-form :model="set" @submit.native.prevent>
                <el-input
                  v-model="set.box_number"
                  @keyup.13.native="enterBox(set.box_number)"
                  placeholder="请通过扫码枪或手动添加创建箱号"
                  ref="inputsbox"
                ></el-input>
              </el-form>
              <el-button type="primary" slot="append" @click="enterBox(set.box_number)">添加</el-button>
            </div>
            <div v-if="show_one" style="margin: 97px auto 0px;text-align: center;">
              <img src="/static/image/device/b-yellow.png">
            </div>
            <vue-scroll :ops="ops" v-show="!show_one">
              <div style="padding:0px;margin-top: 30px;width: 100%;">
                <div
                  v-for="item in arrbox"
                  :key="item.key"
                  style="float: left;width: 280px;height: 50px;margin: 0 7px 15px 7px;box-shadow: 0px 4px 18px rgba(69, 71, 74, 0.1);background: #fff;line-height: 50px;font-size:18px; font-weight:bold;"
                >
                  <img
                    src="/static/image/device/shebei-1.png"
                    style="float:left;margin:8px 5px 0px 12px;"
                  >
                  {{item}}
              
                </div>
              </div>
            </vue-scroll>
          </el-row>
          <!-- 第二步 -->
          <el-row
            :gutter="20"
            v-if="disc_current === 2"
            id="firstCard" 
          >
            <div class="firststorage">
              <el-form :model="form" @submit.native.prevent>
                <el-input
                  v-model="form.imei"
                  @keyup.13.native="enterImei(form.imei)"
                  placeholder="请通过扫码枪或手动添加获取IMEI"
                  ref="inputs"
                ></el-input>
              </el-form>
              <el-button type="primary" slot="append" @click="enterImei(form.imei)">添加</el-button>
            </div>
             <div v-if="show_two" style="margin: 97px auto 0px;text-align: center;">
              <img src="/static/image/device/b-yellow.png">
            </div>  
             <vue-scroll :ops="ops" v-show="!show_two">
              <div style="padding:0px;margin-top: 30px;width: 100%;display: inline-block;">
                <div
                  v-for="item in searchImei"
                  :key="item.key"
                  style="float: left;width: 280px;height: 50px;margin: 0 7px 15px 7px;box-shadow: 0px 4px 18px rgba(69, 71, 74, 0.1);background: #fff;line-height: 50px;font-size:18px; font-weight:bold;"
                >
                  <img
                    src="/static/image/device/shebei-1.png"
                    style="float:left;margin:8px 5px 0px 12px;"
                  >
                  {{item}}
                  <img
                    src="/static/image/device/delect_equment.png"
                    style="float:right;margin:16px;"
                    @click="delectImei(item)"
                  >
                </div>
              </div>
            </vue-scroll>  
           
          </el-row>
          <div class="dialog-footer footer" v-if="disc_current !== 3">
            <el-button
              type="primary"
              class="btnClosed"
              @click="closeDisc"
            >{{disc_current === 2 ? "上一步" : '取消'}}</el-button>
            <el-button
              type="primary"
              @click="next"
              :disabled="can_next"
              class="btnSaved"
              :class="{btnAdd:!can_next,add:can_next}"
            >下一步</el-button>
          </div>
          <!-- 第三步 -->
          <el-row
            :gutter="20"
            style="margin:30px 0 0px 0;"
            v-if="disc_current === 3">
            <img
              src="/static/image/device/b-red.png"
              alt
              style="margin: 20px auto;display: block;"
            >
            <p style="text-align: center;">已入库完成，3s后将自动关闭弹窗</p>
          </el-row>
        </div>
      </el-tabs>
    </template>
  </el-dialog>
</template>
<script>
import Config from "@/config";
import qs from "qs";
import { mapGetters } from "vuex";
export default {
  name: 'PackBox',
  props: ["messageflag"],
  data() {
    return {
      ops: {
        bar: {
          background: "#DDDEE0"
        }
      },
      // 装箱弹框
      dialogTablesVisible: false,
      // 选择第二步点击添加颜色
      disc_current: 1,
      set: {
        box_number: ""
      },
      form: {
        imei: ""
      },
      show_one: true,
      show_two: true,
      arrbox: [], // 装箱子
      searchImei: [], //扫码imei
    };
  },
  methods: {
    // 创建箱子
    enterBox(value) {
        console.log(value)
        console.log(this.arrbox)
        if(value === '') return
        if(this.arrbox.length >= 1){
            this.$message({message: '只能输入单个箱号',type:'warning'})
            this.set.box_number = ""; 
            return
        }
        this.arrbox.push(value)
        this.show_one = false;
        this.set.box_number = "";
    },
     // 扫码搜索设备
    imei_list() {
      return new Promise((resolve, reject) => {
        let url = `${Config.DEVICE_MANAGE_URL}/inventory/query?imei=${this.form.imei}`;
        this.$http.get(url).then(res =>{
            console.log(res)
            if (!res.array.length) {
              this.$message({message: "暂无",type: "error"});
              this.form.imei = ""; 
              return;
            }

            if(res.array[0].current_owner_id === 1){
              this.$message({message: "该设备未入库",type: "error"});
              this.form.imei = ""; 
              return
            } 
            // var devname = res.array.reduce((bool, response) => {
            //     return (bool = !bool
            //     ? bool
            //     : response.devname === bool
            //     ? response.devname
            //     : false);
            // }, res.array[0].devname);
            // if (!devname) {
            //     this.$message.error("设备类型不一致");
            //     return;
            // }
            if (res.array[0].equip_site_id === '' || res.array[0].equip_site_id === null){
                this.searchImei.push(res.array[0].imei); //存储imei
                this.show_two = false;
                this.form.imei = ""; 
                resolve(res);
            }else{
                this.$message({message: "该设备已安装",type: "error"});
                this.form.imei = ""; 
                return
            }
        
        })
      })
    },
    // 判断有没有箱号以及重复
    search_imei() {
      return new Promise((resolve, reject) => { 
        var a = 0;
        if(!this.searchImei.length){
          this.imei_list()
        }else{
        this.searchImei.forEach((item,i) =>{
          if(item === this.form.imei){
            a++;
            this.form.imei = "";
            this.$message({
              message: 'IMEI重复',
              type:'warning'
            })
          }
        })
        if(!a){
          this.imei_list()
        }
      }
      })
    },
    enterImei(value){
        if(value === '') return
        this.search_imei()
    },
    // 扫码删除
    delectImei(value) {
      this.searchImei.map((item, i) => {
        if (item === value) {
          this.searchImei.splice(i, 1);
        }
      });
      this.$message({ type: "success", message: "删除成功!"});
    },
    //imei分配装箱
    next() {
      // 点击下一步
      if (this.disc_current === 1) {
        this.disc_current = 2;
        this.show_one = false;
        this.show_two = true;
        // imei自动获取焦点
        this.$nextTick(() => {
          this.$refs.inputs.focus();
        });
      } else {
        this.$confirm("确定要装箱?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(value => {
            if (value) {
              // 装箱
              this.postbox(); 
              setTimeout(() => {
                this.dialogTablesVisible = false;
              }, 3000);
            }
            this.$message({
              type: "success",
              message: "装箱成功!"
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消装箱"
            });
          });
      }
    },
    // 装箱提交
    postbox() {
        let url = `${Config.DEVICE_MANAGE_URL}/inventory/rebox`;
        // let url = `http://172.16.79.64:8000/DeviceManage/inventory/rebox`;
        // let params = {
        //           box_number: this.arrbox[0],
        //     imei_list: this.searchImei.toString(),
        //     user_id: this.user.id
        // }
        this.$http.post(
          url,
          JSON.stringify({
            box_number: this.arrbox[0],
            imei_list: this.searchImei,
            user_id: this.user.id
          }),
          { "Content-Type": "application/json" }
        )
        .then(res => {
          this.disc_current = 3;
          this.arrbox = [];
          this.$emit('change')
        });
    },
    closeDisc() {
      if (this.disc_current === 1) {
        this.dialogTablesVisible = false;
      } else if (this.disc_current === 2) {
        this.disc_current = 1;
      } else {
        this.dialogTablesVisible = false;
      }
    }
  },
  computed: {
    can_next() {
      if (this.disc_current === 1) {
        if (this.arrbox.filter(res => res).length) {
          return false;
        } else {
          return true;
        }
      }
      if (this.disc_current === 2) {
        if (this.searchImei.filter(res => res).length) {
          return false;
        } else {
          return true;
        }
      }
    },
    ...mapGetters("user", {
      district: "getDistrict",
      role: "getRole",
      user: "getUser"
    })
  },
  watch: {
    messageflag(data) {
      if (data) {
        this.dialogTablesVisible = data;
        this.set.box_number = "";
        this.arrbox = [];
        this.searchImei = [];
        this.show_one = true;
        this.show_two = true
        this.dialogTablesVisible = true;
        this.disc_current = 1;
        // 自动获取焦点
        this.$nextTick(() => {
          this.$refs.inputsbox.focus();
        });
      }
    },

    // 弹框关闭
    dialogTablesVisible(data) {
      if (!data) {
        // 子向父
        this.$emit("listenflag", false);
      }
    }
  }
};
</script>